import React, {Component} from 'react';
import ImagePicker from 'react-native-image-picker';
import {View, WebView, Button} from 'react-native';

const FBSDK = require('react-native-fbsdk');
const {
    LoginManager,
    GraphRequest,
    GraphRequestManager,
    LoginButton
} = FBSDK;


const options = {
    title: 'Select Photo',
    takePhotoButtonTitle: 'Take Photo',
    chooseFromLibraryButtonTitle: 'Choose from library',
};

type Props = {};

// postMessage bug
const patchPostMessageFunction = function () {
    var originalPostMessage = window.postMessage;

    var patchedPostMessage = function (message, targetOrigin, transfer) {
        originalPostMessage(message, targetOrigin, transfer);
    };

    patchedPostMessage.toString = function () {
        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
    };

    window.postMessage = patchedPostMessage;
};

const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';

export default class App extends Component<Props> {
    constructor(props) {
        super(props);

        this.state = {
            avatarSource: null
        }
        this._responseInfoCallback = this._responseInfoCallback.bind(this)
    }

    _responseInfoCallback(error: ?Object, result: ?Object) { // facebook login
        if (error) {
            alert('Error fetching data: ' + error.toString());
        } else {
            // 登录后用户信息回传给webview
            alert(JSON.stringify(result))
            this.refs.webview.postMessage(JSON.stringify(result));
        }
    }

    onMessage(e) {
        /*
         * paramObj.type 指定交互方法
         * 1: facebook login
         * 2: sell 图片调用
         */

        var event = e.nativeEvent;
        // webview 调用rn登录
        let paramObj = JSON.parse(event.data) || {};

        if (paramObj.type && paramObj.type == 1) {  // 调用登录
            LoginManager.logInWithReadPermissions(['public_profile']).then(
                (result) => {
                    if (result.isCancelled) {
                        alert('Login was cancelled');
                    } else {

                        // alert('Login was successful with permissions: ' + result.grantedPermissions.toString() +  `---${dataStr}---`);
                        const infoRequest = new GraphRequest(
                            '/me',
                            {
                                parameters: {
                                    fields: {
                                        string: 'name,picture,token_for_business' // what you want to get
                                    }
                                }
                            },
                            this._responseInfoCallback,
                        );

                        new GraphRequestManager().addRequest(infoRequest).start();
                    }
                },
                function (error) {
                    alert('Login failed with error: ' + error);
                }
            );
            return false;
        } else if (paramObj.type && paramObj.type == 2) {
            ImagePicker.showImagePicker(options, (response) => {
                console.log('Response = ', response);

                if (response.didCancel) {
                    console.log('User cancelled image picker');
                } else if (response.error) {
                    console.log('ImagePicker Error: ', response.error);
                } else {
                    const source = {uri: response.uri};

                    this.setState({
                        avatarSource: source,
                    });


                    var dataIndex = {};
                    if (event.data) {
                        dataIndex = JSON.parse(event.data);
                    }

                    var data = {
                        index: dataIndex.index,
                        data: response.data
                    }

                    this.refs.webview.postMessage(JSON.stringify(data));
                }
            });
        }

        // 获取webivew聊天登录id
        // var userInfo = JSON.parse(event.data) || {};
        // if (userInfo.userId) {
        //     alert(userInfo.userId)
        //     return;  // 防止执行图片上传逻辑
        // }

    }

    render() {
        return (
            <View style={{flex: 1}}>
                <WebView
                    source={{uri: 'https://shopgogo.dlintech.com/'}}
                    ref='webview'
                    style={{flex: 1}}
                    onMessage={this.onMessage.bind(this)}
                    injectedJavaScript={"window.isRNWebView=true;" + patchPostMessageJsCode}
                />
            </View>
        );
    }
}

